﻿/*----------------------------------------------------------------
//  <copyright file="HostHttpCryptoMiddleware.cs" company="MicroCloud@151504200868">
//      Copyright © 2020-2024 MicroCloud Corporation, All rights reserved.
//  </copyright>
//  <site>https://gitee.com/chenmm123/microclouds</site>
//  <last-editor>cmm</last-editor>
//  <last-date>2024-03-04 14:40</last-date>
//----------------------------------------------------------------*/

namespace MicroCloud.AspNetCore.Http
{
    #region "服务端通信加密解密中间件，对请求进行解密，对响应进行加密，如使用，请将此中间件放在第一个"
    /// <summary>
    /// 服务端通信加密解密中间件，对请求进行解密，对响应进行加密，如使用，请将此中间件放在第一个
    /// </summary>
    public class HostHttpCryptoMiddleware : IMiddleware
    {
        //字段
        private readonly RequestDelegate _next;
        private readonly IHostHttpCrypto _hostHttpCrypto;

        #region "构造函数"
        #region "初始化一个服务端通信加密解密中间件的新实例"
        /// <summary>
        /// 初始化一个服务端通信加密解密中间件 <see cref="HostHttpCryptoMiddleware"/> 的新实例
        /// </summary>
        /// <param name="next"></param>
        /// <param name="hostHttpCrypto"></param>
        public HostHttpCryptoMiddleware(RequestDelegate next, IHostHttpCrypto hostHttpCrypto)
        {
            _next = next;
            _hostHttpCrypto = hostHttpCrypto;
        }
        #endregion

        #endregion

        #region "方法"
        #region "执行中间件拦截逻辑"
        /// <summary>
        /// 执行中间件拦截逻辑
        /// </summary>
        /// <param name="context">Http上下文</param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            HttpRequest request = context.Request;
            await _hostHttpCrypto.DecryptRequest(request);
            await _next(context);
            HttpResponse response = context.Response;
            await _hostHttpCrypto.EncryptResponse(response);
        }
        #endregion

        #endregion

    }
    #endregion

}
